/**
 * @apiDefine wechat_open 开放平台授权
 */
const Base = require('./base')
const moment = require('moment')
module.exports = class extends Base {
  constructor (...args) {
    super(...args)
    this.wxopen = this.service('open')
    this.conf = this.config('wxopen')
  }

  async tokenAction () {
    const t = this.get('t')
    yy.log.debug(t)
    const d = await this.cache('component_access_token', t)
    this.body = d
  }

  async ticketAction () {
    const t = this.get('t')
    yy.log.debug(t)
    const d = await this.cache('component_verify_ticket', t)
    this.body = d
  }

  /**
   * 同步现有应用数据 临时api
   */
  async syncAction () {
    const { appid } = this.conf
    const token = this.cache('component_access_token')
    const list = await yy.http.post(`https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_list?component_access_token=${token}`, {
      component_appid: appid, offset: 0, count: 100
    })
    list.list.map(v => {
      yy.model('wx_authorizer').sync(v)
    })
    this.body = list
  }
  async getAccountAction () {
    const appid = this.get('appid')
    const d = await this.wxopen.getBaseInfo(appid)
    this.body = d
  }
  async refreshComponentTokenAction () {
    const d = await this.wxopen.refreshComponentToken()
    this.body = d
  }

  /**
     * @api {post} /wechat/open/auth 授权事件接收URL
     * @apiDescription 在公众号第三方平台创建审核通过后，微信服务器会向其“授权事件接收URL”每隔10分钟定时推送component_verify_ticket。第三方平台方在收到ticket推送后也需进行解密
     * @apiVersion 1.0.0
     * @apiGroup wechat_open
     * @apiPermission admin
     * @apiParam {String} xmlPost 微信xml内容
     * @apiSuccess {Number} code 0
     * @apiSuccess {String} msg ''
     * @apiSuccess {Json} data {}
     */
  async authAction () {
    const d = this.post('xml')
    yy.log.info(`=======wechat open auth====${JSON.stringify(d)}===${moment().format('YYYY-MM-DD HH:mm:ss')}===============`)
    if (d) {
      d.msg_signature = this.get('msg_signature')
      d.nonce = this.get('nonce')
      d.timestamp = this.get('timestamp')
      const oauth = await this.wxopen.getComponentVerifyTicket(d)
      yy.log.info('========authorizer==========', JSON.stringify(oauth || {}))
      // 取消授权
      if (oauth.InfoType === 'unauthorized') {
        // await this.model('wx_authorizer').refreshStatus(oauth, 0)
      } else if (oauth.InfoType === 'updateauthorized') {
        await this.model('wx_authorizer').refreshStatus(oauth, 1)
      } else {
        // 更新授权 授权
        const verifyTicket = oauth.ComponentVerifyTicket
        yy.log.info('=== verifyTicket=== ', verifyTicket)
        const accessToken = await this.wxopen.getComponentAccessToken(verifyTicket)
        yy.log.info('=== accessToken=== ', accessToken)
        const preAuthCode = await this.wxopen.getPreAuthCode(accessToken)
        yy.log.info('=== preAuthCode=== ', preAuthCode)
      }
    }
    // 4、模拟推送component_verify_ticket给开发者，开发者需按要求回复（接收到后必须直接返回字符串success）。
    this.body = 'success'
  }

  /**
     * @api {post} /wechat/open/getauth 二维码扫描页面
     * @apiDescription 二维码扫描页面 测试地址 https://mp.vco.fun/wechat/open/getauth
     * @apiVersion 1.0.0
     * @apiGroup wechat_open
     * @apiPermission admin
     * @apiParam {String} url 跳转二维码页面链接
     * @apiSuccess redirect url
     */
  async getauthAction () {
    let url = this.get('from_url') || this.ctx.referer
    url = await this.wxopen.getAuthUrl(url)
    yy.log.debug(url)
    return this.redirect(url)
  }

  /**
     * ::TODO 授权后返回的地址需要添加
     * @api {post} /wechat/open/signin 授权后返回地址
     * @apiDescription 授权之后返回的页面
     * @apiVersion 1.0.0
     * @apiGroup wechat_open
     * @apiPermission admin
     * @apiParam {String[]} get 接口信息返回信息
     * @apiSuccess {redirect} redirect 待完善?
     */
  async signinAction () {
    const getData = this.get()
    yy.log.info('signin getData', getData)
    const d = await this.wxopen.getApiQueryAuth(getData)
    if (d && d.authorizer_appid) {
      const cb = await this.wxopen.getBaseInfo(d.authorizer_appid)
      yy.log.info(cb)
    }
    if (getData.from_url) return this.redirect(getData.from_url || '/')
  }

  /* testAction() {
        this.display()
    } */
}
